#!/usr/bin/env perl

use strict;
use warnings;

my $executable = $ARGV[0];
my $out_dir    = $ARGV[1];

open(my $fh, "-|", "ldd", $executable) or die $!;

while (my $line = <$fh>) {
    chomp $line;

#    libavformat.so.52 => /usr/lib/i686/cmov/libavformat.so.52 (0x003a2000)

    if ($line =~ /^\s(\S+) => (\S+) \(0x[0-9a-f]+\)$/) {
        my $lib = $2;

        print "library $lib ";

        if (-l $lib) {
            print " => ".readlink($lib);

            my $actual_library_leaf = readlink($lib);

            system("cp", "-v", $lib, "$out_dir/$actual_library_leaf")==0 or die "copy failed";

            $lib =~ /([^\/]+$)/;
            my $generic_library_leaf = $1;

            symlink($actual_library_leaf, "$out_dir/$generic_library_leaf") or die $!;
        }
        else {
            system("cp", "-v", $lib, "$out_dir/")==0 or die "copy failed";
        }
    }
    else {
        warn "could not parse: $line";
    }
}
